<template>
  <div class="product-detail-container" v-loading="loading">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span>商品详情</span>
          <div>
            <el-button @click="$router.go(-1)">返回</el-button>
            <el-button type="primary" @click="showEditDialog" v-if="product">编辑</el-button>
            <el-button type="danger" @click="confirmDelete" v-if="product">删除</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="product" class="detail-content">
        <div class="image-container">
          <img 
            :src="getImageUrl(product.path)" 
            alt="商品图片"
            class="detail-image"
            @error="handleImageError"
          />
        </div>
        <div class="info-container">
          <h2>{{ product.name }}</h2>
          <div class="price">¥{{ product.price?.toFixed(2) || '0.00' }}</div>
          <p class="meta-info">
            <span>商品ID: {{ product.id }}</span>
            <span>上传时间: {{ formatDate(product.uploadTime) }}</span>
          </p>
          <el-divider />
          <div class="description">
            <h3>商品描述</h3>
            <p>{{ product.overview || '暂无描述' }}</p>
          </div>
        </div>
      </div>
      <el-empty v-else description="找不到该商品" />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑商品信息" width="50%">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="商品名称">
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input-number v-model="editForm.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input 
            v-model="editForm.overview" 
            type="textarea" 
            :rows="5" 
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit" :loading="updating">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import api from '../../services/api';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const product = ref(null);
const loading = ref(false);
const updating = ref(false);
const editDialogVisible = ref(false);
const editForm = ref({
  name: '',
  price: 0,
  overview: ''
});

const getImageUrl = (path) => {
  return `http://localhost:9000${path}`;
};

const handleImageError = (e) => {
  e.target.src = 'https://via.placeholder.com/300x300?text=Image+Not+Found';
};

const formatDate = (dateString) => {
  if (!dateString) return '未知时间';
  return dateString.split('T')[0];
};

const fetchProductDetail = async () => {
  try {
    loading.value = true;
    const response = await api.getProductDetail(route.params.id);
    product.value = response.data;
  } catch (error) {
    ElMessage.error('获取商品详情失败: ' + error.message);
  } finally {
    loading.value = false;
  }
};

const showEditDialog = () => {
  if (product.value) {
    editForm.value = {
      name: product.value.name,
      price: product.value.price || 0,
      overview: product.value.overview || ''
    };
  }
  editDialogVisible.value = true;
};

const submitEdit = async () => {
  if (!editForm.value.name.trim()) {
    ElMessage.warning('请输入商品名称');
    return;
  }

  try {
    updating.value = true;
    await api.updateProduct(route.params.id, editForm.value);
    ElMessage.success('商品信息更新成功');
    await fetchProductDetail();
    editDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.response?.data?.message || error.message));
  } finally {
    updating.value = false;
  }
};

const confirmDelete = () => {
  ElMessageBox.confirm(
    '确定要删除这个商品吗？此操作不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      loading.value = true;
      await api.deleteProduct(route.params.id);
      ElMessage.success('商品删除成功');
      router.push('/goods');
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message));
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 用户点击了取消
  });
};

onMounted(() => {
  fetchProductDetail();
});
</script>

<style scoped>
.product-detail-container {
  padding: 20px;
}
.detail-card {
  max-width: 1000px;
  margin: 0 auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-content {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
}
.image-container {
  flex: 1;
  min-width: 300px;
  text-align: center;
}
.detail-image {
  max-width: 100%;
  max-height: 500px;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.info-container {
  flex: 2;
  min-width: 300px;
}
.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}
.meta-info {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
  margin-top: 10px;
}
.description {
  margin: 20px 0;
}
.description h3 {
  margin-bottom: 10px;
}
</style>